; 递归版
(define (sum term a next b)
    (if (> a b)
        0
        (+ (term a) (sum term (next a) next b))))

(define (product term a next b)
    (if (> a b)
        1
        (* (term a) (product term (next a) next b))))

; 迭代版
(define (sum term a next b)
    (define (iter a reslut)
        (if (> a b)
            reslut
            (iter (next a) (+ (term a) reslut))))
    (iter a 0))

(define (product term a next b)
    (define (iter a reslut)
        (if (> a b)
            reslut
            (iter (next a) (* (term a) reslut))))
    (iter a 1))

; 递归版
(define (accumulate combiner null-value term a next b)
    (if (> a b)
        null-value
        (combiner (term a) (accumulate combiner null-value term (next a) next b))))

; 迭代版
(define (accumulate combiner null-value term a next b)
    (define (iter a reslut)
        (if (> a b)
            reslut
            (iter (next a) (combiner (term a) reslut))))
    (iter a null-value))

; 测试过程
(define (identity x) x)
(define (next a) (+ a 1))

; 借助 accumulate 实现阶乘
(define combiner-p *)
(define (fp n)
    (accumulate combiner-p 1 identity 1 next n))

; 借助 accumulate 实现连续求和
(define combiner-s +)
(define (fs n)
    (accumulate combiner-s 0 identity 1 next n))

(display "\n========================================\n")
(display (fp 6))
(newline)
(display (fs 10))
(display "\n========================================\n")
